package com.example.presentshopping.ui.activity

import android.Manifest
import android.app.AlertDialog
import android.app.Dialog
import android.content.pm.PackageManager
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.config.base.MyApplication.getContext
import com.example.presentshopping.config.bean.CodeBean
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.utils.ShareUtils
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.tool.GsonUtils
import com.example.presentshopping.utils.tool.unit.DensityUtil
import com.permissionx.guolindev.PermissionX
import com.yun.utils.image.ImageUtils
import com.yun.utils.image.ImageUtils.saveImageToFile
import com.yun.utils.image.QRCodeUtil
import com.yun.utils.image.SizeUtils
import kotlinx.android.synthetic.main.activity_rq_code.*
import java.io.File

class RqCodeActivity : BaseMvpActivity() {

    var sendMesPresenter: PublicPresenter? = null
    var codeBean: CodeBean? = null
    private var bitmap_1: Bitmap? = null

    override val layoutId: Int
        get() = R.layout.activity_rq_code

    override fun initView(savedInstanceState: Bundle?) {
        sendMesPresenter = PublicPresenter(this, false, "")
        sendMesPresenter?.attachView(this)
        bcak_iv.setOnClickListener { finish() }

        Rqcode()
        // SD卡根目录
        val sdRoot = Environment.getExternalStorageDirectory()
        val file = File(sdRoot, "RqCode" + ".png")
        Log.e("RqCodeActivity", "" + file)
        button.setOnClickListener {
            if (ActivityCompat.checkSelfPermission(
                    context!!,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            ) {
                PermissionX.init(this)
                    .permissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                    .onExplainRequestReason { scope, deniedList ->
//                        val message = "需要您同意以下权限才能正常使用"
//                        scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
                    }
                    .request { allGranted, grantedList, deniedList ->
                        if (allGranted) {
                            var file = ImageUtils.saveImageToFile(this@RqCodeActivity, bitmap_1!!, "invite_face.jpg")
                            ShareUtils.shareWechatFriend(context, "" + file)
                        } else {

                        }
                    }

            } else {
                var file = ImageUtils.saveImageToFile(this@RqCodeActivity, bitmap_1!!, "invite_face.jpg")
                ShareUtils.shareWechatFriend(context, "" + file)
            }




        }

    }



    fun Rqcode() {
        sendMesPresenter?.setHaveCode(false)
        sendMesPresenter?.netWorkRequestGet(HttpURL.Req_getRcode)
    }

    override fun showToast(msg: String?) {


    }

    override fun onSuccess(data: String?) {

        codeBean = GsonUtils.getGson().fromJson(data, CodeBean().javaClass)

        Log.e("RqCodeActivity", "" + codeBean?.register_url)

        val logoBitmap = BitmapFactory.decodeResource(resources, R.mipmap.iconi)
        // 生成二维码。
//        val mBitmap = QRCodeEncoder.syncEncodeQRCode(
//            codeBean?.register_url, DensityUtil.dip2px(getContext(), 200f),
//            Color.parseColor("#333333"), logoBitmap
//        )
        codeBean?.register_url?.let { RCDemo(it) }


    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    override fun onDestroy() {
        sendMesPresenter?.detachView()
        super.onDestroy()
    }
    //合成图片
    fun mergeBitmap(firstBitmap: Bitmap?, secondBitmap: Bitmap?, width: Float, height: Float, type: Int): Bitmap? {
        if (firstBitmap == null || secondBitmap == null) return null
        val bitmap = Bitmap.createBitmap(
            firstBitmap.width, firstBitmap.height,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        canvas.drawBitmap(firstBitmap, 0f, 0f, null)
        //NULL

        when (type) {
            0, 1 -> {
                // 画笔。
                val paint = Paint()
                paint.color = Color.WHITE
                paint.style = Paint.Style.FILL
                paint.strokeWidth = 12f
                paint.textSize = SizeUtils.dip2px(this, 20f)
                val msg = ""
                //绘制到图片上。在图片上位置
                canvas.drawText(
                    msg,
                    SizeUtils.dip2px(this, 0f),
                    SizeUtils.dip2px(this, 0f),
                    paint
                )
            }
            2 -> {
                val paint = Paint()
                paint.color = Color.WHITE
                paint.style = Paint.Style.FILL
                paint.strokeWidth = 12f
                paint.textSize = SizeUtils.dip2px(this, 20f)
                val msg = ""
                canvas.drawText(
                    msg,
                    SizeUtils.dip2px(this, 30f),
                    SizeUtils.dip2px(this, 20f),
                    paint
                )
            }

        }

        canvas.save()
        canvas.drawBitmap(secondBitmap, width, height, null)
        canvas.restore()
        return bitmap
    }
    fun RCDemo(url : String) {
//        val logoBm = QRCodeUtil.createQRCodeBitmap(url, SizeUtils.dip2px(this, 100f).toInt(), SizeUtils.dip2px(this, 100f).toInt())
        val logoBitmap = BitmapFactory.decodeResource(resources, R.mipmap.iconi)
        val logoBm = QRCodeEncoder.syncEncodeQRCode(
            url, DensityUtil.dip2px(getContext(), 100f),
            Color.parseColor("#333333"), logoBitmap)
        val bm1 = (resources.getDrawable(R.mipmap.fenx1) as BitmapDrawable).bitmap
        bitmap_1 = mergeBitmap(bm1, logoBm, SizeUtils.dip2px(this, 118f), SizeUtils.dip2px(this, 500f), 0)

        lian_rasie?.setImageBitmap(bitmap_1)
    }

}